package com.sxbbc.plat.controller.jz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.utils.statics.EnumUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.ClassifyTypeEnums;
import com.sxbbc.common.core.enums.EventEnums;
import com.sxbbc.common.core.enums.ModelTypeEnums;
import com.sxbbc.common.core.enums.PositionDailyEnums;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.common.core.utils.FileUtils;
import com.sxbbc.common.core.utils.MultipartFileToFile;
import com.sxbbc.plat.common.AppHomeMapping;
import com.sxbbc.plat.util.SystemLog;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.util.List;

/**
 * 活动/活动有关 控制层
 *
 * @author leehao
 * @date 2019-05-25 09:53
 */
@Controller
public class AppHomeController {

    @Autowired
    private IActivityDailyService activityDailyService;
    @Autowired
    private IAppHomeModelService appHomeModelService;
    @Autowired
    private IAppHomeRecommendService recommendService;
    @Autowired
    private IProcMainService procMainService;
    @Autowired
    private ProcClassifyMainService classifyMainService;
    @Autowired
    private ProcClassifyMainService procClassifyMainService;

    /**
     * 活动管理-app首页版块管理
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = AppHomeMapping.SHOW_APP_HOME_ACTIVITY)
    public ModelAndView showAppHomeActivity(){
        List<AppHomeModel> list = appHomeModelService.list();
        list.forEach(x -> x.setModelName(ModelTypeEnums.getName(x.getModelType())));
        ModelAndView view = new ModelAndView(AppHomeMapping.SHOW_APP_HOME_ACTIVITY);
        view.addObject("list",list);
        return view;
    }

    /**
     * 编辑版块信息页面
     * @param id /
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = AppHomeMapping.SHOW_EDIT_APP_HOME_ACTIVITY)
    public ModelAndView showEditAppHomeActivity(Integer id){
        AppHomeModel model = appHomeModelService.getById(id);
        List<ModelTypeEnums> modelList = ModelTypeEnums.queryList();
        ModelAndView view = new ModelAndView(AppHomeMapping.SHOW_EDIT_APP_HOME_ACTIVITY);
        view.addObject("model",model);
        view.addObject("modelList",modelList);
        return view;
    }

    /**
     * 编辑版块信息方法
     * @param model 对象
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = AppHomeMapping.EDIT_APP_HOME_ACTIVITY)
    @ResponseBody
    @SystemLog(methods = "保存App首页活动版块",module = "活动管理")
    public RestResponse editAppHomeActivity(AppHomeModel model){
        if (StringUtils.isBlank(model.getName())) {
            return GetRest.getFail("请输入版块名称");
        }
        if (model.getModelType() == null) {
            return GetRest.getFail("请选择版块模版类型");
        }
        boolean save = appHomeModelService.saveOrUpdate(model);
        if (!save) {
            throw new ThrowJsonException("保存首页版块信息失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 处理版块显示隐藏
     * @param model display属性
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = AppHomeMapping.HANDLE_APP_HOME_DISPLAY)
    @ResponseBody
    @SystemLog(methods = "更新app活动版块显示状态",module = "活动管理")
    public RestResponse handleAppHomeActivityDisplay(AppHomeModel model){
        boolean update = appHomeModelService.updateById(model);
        if (!update) {
            throw new ThrowJsonException("操作活动信息失败");
        }
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 活动管理-每日必逛页面
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = AppHomeMapping.SHOW_ACTIVITY_DAILY)
    public ModelAndView showActivityDaily(Integer parentId){
        List<ActivityDaily> list = activityDailyService.list();
        list.forEach(x -> x.setEventName(EventEnums.getName(x.getEvent())));
        ModelAndView view = new ModelAndView(AppHomeMapping.SHOW_ACTIVITY_DAILY);
        view.addObject("list",list);
        view.addObject("parentId",parentId);
        return view;
    }

    /**
     * 编辑每日必逛页面
     * @param id 记录id
     * @param position 位置标记
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = AppHomeMapping.SHOW_EDIT_ACTIVITY_DAILY)
    public ModelAndView showEditDaily(Integer id,Integer position){
        QueryWrapper<ActivityDaily> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id).eq("position",position);
        ActivityDaily daily = activityDailyService.getOne(wrapper);
        List<EventEnums> allList = EventEnums.queryAllList();
        //跳转分类事件
        EventEnums classify = EventEnums.CLASSIFICATION;
        //状态可用的一级分类
        ProcThirdClassifyMain thirdClassifyMain = new ProcThirdClassifyMain();
        thirdClassifyMain.setLevel(StaticUtils.FIRST_CLASSIFY);
        List<?> firstList = procClassifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        String[] classList = daily.getUrl().split(",");
        daily.setFirstClass(Integer.parseInt(classList[0]));
        daily.setSecondClass(Integer.parseInt(classList[1]));
        List<?> secondList = procClassifyMainService.queryClassifyListAjax
                (Integer.parseInt(classList[0]), ClassifyTypeEnums.PLAT_FORM.getId(),
                        null,StaticUtils.SECOND_CLASSIFY);
        ModelAndView view = new ModelAndView(AppHomeMapping.SHOW_EDIT_ACTIVITY_DAILY);
        view.addObject("daily",daily);
        view.addObject("classify",classify);
        view.addObject("firstList",firstList);
        view.addObject("secondList",secondList);
        view.addObject("position", EnumUtils.getEnum(PositionDailyEnums.class, EnumUtils.GET_ID, daily.getPosition()));
        return view;
    }

    /**
     * 编辑每日必逛
     * @param daily /
     * @param imgUrl 图片
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = AppHomeMapping.EDIT_ACTIVITY_DAILY)
    @ResponseBody
    @SystemLog(methods = "保存必逛活动信息",module = "活动管理")
    public RestResponse editActivityDaily(ActivityDaily daily,
                      @RequestParam(required = false) MultipartFile imgUrl){
        if (daily.getFirstClass() == null) {
            return GetRest.getFail("请选择一级分类");
        }
        if (daily.getSecondClass() == null) {
            return GetRest.getFail("请选择二级分类");
        }
        String url = daily.getFirstClass()+","+daily.getSecondClass();
        daily.setUrl(url);
//        RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(imgUrl);
//        if (result.isStatus()) {
//            daily.setIcon(result.getData());
//        }else if(!result.isStatus() && imgUrl != null){
//            return GetRest.getFail("图片上传失败");
//        }
        try {
            File fe= MultipartFileToFile.multipartFileToFile(imgUrl);
            String path= FileUtils.up(fe);
            daily.setIcon(path);
        }catch (Exception e){
            return GetRest.getFail("上传图片失败");
        }
        boolean save = activityDailyService.updateById(daily);
        if (!save) {
            throw new ThrowJsonException("保存每日必逛活动失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 推荐商品版块页面
     * @param parentId /
     * @param page 分页对象
     * @param recommend 查询对象
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = AppHomeMapping.SHOW_RECOMMEND_PRODUCT)
    public ModelAndView showRecommendProc(Integer parentId, BasePage<AppHomeRecommend> page, AppHomeRecommend recommend){
        IPage<AppHomeRecommend> pageInfo = recommendService.queryRecommendList(page,recommend);
        ModelAndView view = new ModelAndView(AppHomeMapping.SHOW_RECOMMEND_PRODUCT);
        view.addObject("pageInfo",pageInfo);
        view.addObject("parentId",parentId);
        return view;
    }

    /**
     * 显示添加推荐商品页面
     * @param parentId /
     * @param page 分页对象
     * @param procMain 查询对象
     *                 一二三级分类查询
     *                 商品编码查询
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = AppHomeMapping.SHOW_ADD_RECOMMEND)
    public ModelAndView showAddRecommend(Integer parentId, BasePage<AppHomeRecommend> page, ProcMain procMain){
        page.setSize(5);
        IPage<AppHomeRecommend> pageInfo = procMainService.queryRecommendProc(page,procMain);
        //分类
        ProcThirdClassifyMain thirdClassifyMain = new ProcThirdClassifyMain();
        thirdClassifyMain.setLevel(StaticUtils.FIRST_CLASSIFY);
        List<?> firstList = classifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        ModelAndView view = new ModelAndView(AppHomeMapping.SHOW_ADD_RECOMMEND);
        view.addObject("parentId",parentId);
        view.addObject("pageInfo",pageInfo);
        view.addObject("firstList",firstList);
        return view;
    }

    /**
     * 添加推荐商品
     * @param skuDetailId 规格id
     * @param proCode 商品编码
     * @param parentId /
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = AppHomeMapping.ADD_RECOMMEND)
    @ResponseBody
    public RestResponse addRecommend(Integer skuDetailId,String proCode,Integer parentId){
        if (StringUtils.isBlank(proCode)) {
            return GetRest.getFail("请选中商品后再保存提交");
        }
        AppHomeRecommend recommend = new AppHomeRecommend();
        recommend.setPid(parentId);
        recommend.setProCode(proCode);
        recommend.setProSkuId(skuDetailId);
        boolean save = recommendService.save(recommend);
        if (!save) {
            throw new ThrowJsonException("添加推荐商品失败");
        }
        return GetRest.getSuccess("添加成功");
    }

    /**
     * 取消推荐商品
     * @param id 推荐记录的id
     * @author leehao
     * @return boolean
     */
    @RequestMapping(value = AppHomeMapping.DELETE_RECOMMEND)
    @ResponseBody
    public boolean delRecommend(Integer id){
        boolean delete = recommendService.removeById(id);
        if (!delete) {
            throw new ThrowJsonException("取消推荐失败");
        }
        return delete;
    }
}
